import {getRequest} from "@/utils/api";

export const initMenu = (router, store) =>{
    if (store.state.routes.length>0){
        return;
    }

    getRequest('/system/config/menu').then(
        data =>{
            if (data){
                // 将后端返回的菜单信息解析成符合router的对象
                let fmtRouter = formatRouters(data)
                // 将解析结果添加到router中
                router.addRoutes(fmtRouter);
                // 将格式化好的结果存入vuex
                store.commit('initRoutes', fmtRouter);
                // 连接websocket
                // store.dispatch('connect');
            }
        }
    )
}

export const formatRouters = (routes) =>{
    let fmtRouters = [];
    routes.forEach(route =>{
        // 在route中取出这些值
        let {
            path,
            component,
            name,
            iconCls,
            children
        } = route;
        // 如果存在子路由
        if (children && children instanceof Array){
            // 递归解析
            children = formatRouters(children);
        }
        // 解析完成之后构建准备放入router的对象
        let fmRouter = {
            path,
            name,
            iconCls,
            children,
            // 因为此处后端传回来的component字段只是组件名，我们需要根据这个组件名拿到该组件
            // 所以此处采用ES5的写法根据组件名拼接组件路径导入组件
            component(resolve){
                if (component.startsWith('Emp')){
                    require(['../views/emp/'+component+'.vue'],resolve);
                } else if (component.startsWith('Per')){
                    require(['../views/per/'+component+'.vue'],resolve);
                } else if (component.startsWith('Sal')){
                    require(['../views/sal/'+component+'.vue'],resolve);
                } else if (component.startsWith('Sta')){
                    require(['../views/sta/'+component+'.vue'],resolve);
                } else if (component.startsWith('Sys')){
                    require(['../views/sys/'+component+'.vue'],resolve);
                }else {
                    require(['../views/' + component + '.vue'], resolve);
                }
            }
        }
        // 将解析结果放入准备好的数组
        fmtRouters.push(fmRouter);
    })
    // 返回解析好的结果
    return fmtRouters;
}